;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.Storefront", [])
        .controller("StorefrontCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
            $scope.selectedData = {
                warehouse: {}
            };

            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {
                cueRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.provinceList = [];
            $scope.cityList = [];
            $scope.areaList = [];
            $scope.detailInfo = {isEnable: "1"};
            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };
            $scope.tbConf = {
                fixedWidth: 150,
                scrollWidth: 1420,
                tableCol: [
                    {
                        type: "",
                        name: "网点名称",
                        width: 150,
                        dataField: "storeName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户编号",
                        width: 150,
                        dataField: "dealerCode",
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        width: 150,
                        dataField: "dealerName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "省",
                        width: 150,
                        dataField: "province",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "市",
                        width: 150,
                        dataField: "city",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "区",
                        width: 150,
                        dataField: "area",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },

                    {
                        type: "",
                        name: "详细地址",
                        width: 150,
                        dataField: "addreass",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系人",
                        width: 150,
                        dataField: "contactName",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系电话",
                        width: 150,
                        dataField: "contactTel",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否启用",
                        width: 150,
                        dataField: "isEnable",
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },


                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 110,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            var btnPermissionCode = {
                storefrontAdd: window.ActionCode.storefrontAdd,
                storefrontEdit: window.ActionCode.storefrontEdit,
                storefrontDel: window.ActionCode.storefrontDel
            };

            $scope.btnPermission = {
                storefrontAdd: true,
                storefrontEdit: true,
                storefrontDel: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }


            $scope.setFixedWidth = function () {
                $scope.tbStyle = {scrollLeft: {left: $scope.tbConf.fixedWidth + "px"}};
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {isEnable: "1"};
                $scope.provinceList = [];
                $scope.cityList = [];
                $scope.areaList = [];
                $scope.selectedData = {
                    warehouse: {}
                };
            }

            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/storefront/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    angular.forEach(resp.value.list, function (item) {
                        item.isEnable = item.isEnable === 0 ? '否' : '是';
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.addData = function () {
                initData();
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.getProvince();
                $scope.changeTab(1);
            };

            $scope.delData = function (storeId) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/storefront/delete";
                    var param = {};
                    param.storeId = storeId;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.editData = function (item) {
                getStoreItem(item.storeId).then(function (data) {
                    $scope.detailInfo = data.value;
                    $scope.changeTab(1);
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.getProvince();

                    $scope.selectedData = {
                        warehouse: {
                            ids: $scope.detailInfo.warehouseCodes || []
                        },
                        crmAgent: $scope.crmAgentNameList.find(c => c.crmAgentCode == $scope.detailInfo.crmAgentCode),
                        serviceStation: $scope.serviceStatioNameList.find(c => c.serviceStationCode == $scope.detailInfo.serviceStationCode)
                    };
                    getWarehousesList();
                });
            };

            function getStoreItem(storeId) {
                var service = "device";
                var reqUrl = "/storefront/item";
                var param = {};
                param.storeId = storeId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            }

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/storefront/addStore";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/storefront/update";
                }
                const { crmAgentCode = '', crmAgentName = '' } = $scope.selectedData.crmAgent || {}
                const param = {
                    ...angular.copy($scope.detailInfo),
                    warehouseCodes: $scope.selectedData.warehouse.ids,
                    crmAgentCode, crmAgentName,
                    ...$scope.selectedData.serviceStation
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.selectDealer = function () {
                ybWidget.DataSelector({
                    title: '客户',
                    url: '/companyDealer/listOrgDealer',
                    keyWords: [{label: '客户编号', field: 'dealerCode'}, {label: '客户名称', field: 'companyName'}],
                    fields: [
                        {
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        }
                    ]
                }).then(function (data) {
                    $scope.detailInfo.dealerName = data.companyName;
                    $scope.detailInfo.dealerCode = data.dealerCode;
                    $scope.detailInfo.dealerOrgId = data.dealerOrgId;
                    $scope.detailInfo.platOrgId = data.platOrgId;
                    getWarehousesList();
                })
            };


            //获取省份方法
            $scope.getProvince = function () {
                var service = "device";
                var reqUrl = "/areaInfo/allProvince";
                getCity(service, reqUrl).then(function (data) {
                    if (!!data) {
                        $scope.provinceList = data;
                    }
                })
            };

            $scope.$watch("detailInfo.provinceId", function (newValue) {
                if (!!newValue) {
                    $scope.getCity("city", newValue, false);
                    if (!!$scope.detailInfo.cityId) {
                        $scope.getCity("area", $scope.detailInfo.cityId, false);
                    }
                }
            });

            // 获取所在地区 省/市/县
            function getCity(service, reqUrl, param) {
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return false;
                    }
                    return resp.value;
                });
            }

            function getAreaName(areaLevel, cityCode) {
                for (var i = 0; i < $scope[areaLevel + "List"].length; i++) {
                    var item = $scope[areaLevel + "List"][i];
                    if (cityCode == item[areaLevel + "Id"]) {
                        $scope.detailInfo[areaLevel] = item[areaLevel];
                        break;
                    }
                }
            }

            $scope.getCity = function (district, cityCode, isSelectChange) {
                var reqUrl = "";
                var param = {father: cityCode};
                var service = "device";
                if (district === "city") {
                    $scope.cityList = []
                    $scope.areaList = [];
                    if (isSelectChange) {
                        $scope.detailInfo.city = ''
                        $scope.detailInfo.cityId = ''
                        $scope.detailInfo.area = ''
                        $scope.detailInfo.areaId = ''
                    }
                    if (cityCode == null) {
                        $scope.detailInfo.province = ''
                        $scope.detailInfo.provinceId = ''
                        return
                    }

                    reqUrl = "/areaInfo/cityByProvince";
                    getAreaName("province", cityCode);
                } else if (district === "area") {
                    $scope.areaList = [];
                    if (isSelectChange) {
                        $scope.detailInfo.area = ''
                        $scope.detailInfo.areaId = ''
                    }
                    if (cityCode == null) {
                        $scope.detailInfo.city = ''
                        $scope.detailInfo.cityId = ''
                        return
                    }

                    reqUrl = "/areaInfo/areaByCity";
                    getAreaName("city", cityCode);
                } else {
                    if (cityCode == null) {
                        $scope.detailInfo.area = ''
                        $scope.detailInfo.areaId = ''
                        return
                    }
                    getAreaName("area", cityCode);
                    return
                }

                getCity(service, reqUrl, param).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope[district + "List"] = data;
                });
            };

            function getWarehousesList() {
                if (!$scope.isJCH) return;
                var service = "device";
                var reqUrl = "/warehouse/listUnBindSiteWareHouse";
                var param = {
                    siteId: $scope.detailInfo.storeId,
                    dealerOrgId: $scope.detailInfo.dealerOrgId,
                    platOrgId: $scope.detailInfo.platOrgId,
                    pageNum: 0,
                    pageSize: 0
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const datasT = resp.value && resp.value.list ? resp.value.list : []
                    angular.forEach(datasT, function (item) {
                        item.isChecked = false;
                    });
                    $scope.warehousesSource = datasT;
                });
            }
            $scope.handleWarehouseClick = function() {
                if (!$scope.detailInfo.dealerOrgId) {
                    ybWidget.ShowMessage('请先选择客户', MESG_TYPE.Error);
                    return false
                }
                return true
            };

            $scope.crmAgentNameList = [];
            $scope.serviceStatioNameList = [];
            function getCrmStations() {
                if (!$scope.isJCH) return;
                ybHttp.Get('device', '/crm4Jc/crmStations', {}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.crmAgentNameList = resp.value.agents.filter(s => !!s.crmAgentCode); // 网点列表
                    $scope.serviceStatioNameList = resp.value.services.filter(s => !!s.serviceStationCode); // 服务站列表
                });
            }

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                getCrmStations();
            })();
        }])
    ;
})(window, window.angular);